package com.ticket.sass.admin.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.ticket.sass.admin.manager.MybatisTenantIgnoreManager;
import com.ticket.sass.admin.manager.ThreadLocalIdInputHolderManager;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author ywb
 * @date 2024-03-20 10:52
 */
@Component
public class MyTenantHandler implements TenantLineHandler {
    
    private final HttpServletRequest request;
    
    public MyTenantHandler(HttpServletRequest request) {
        this.request = request;
    }
    
    
    @Override
    public Expression getTenantId() {
        IdentityInput identityInput = ThreadLocalIdInputHolderManager.getValue();
        
        return new LongValue(identityInput.getTenantId());
    }
    
    @Override
    public String getTenantIdColumn() {
        return TenantLineHandler.super.getTenantIdColumn();
    }
    
    
    // 要忽略的表列表
    private static final List<String> IGNORED_TABLES = Arrays.asList("areas", "films", "film_versions", "apps","tenants","resources",
        "films",
        "film_versions",
        "apps");
    
    // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
    @Override
    public boolean ignoreTable(String tableName) {
        MybatisTenantIgnoreManager.IgnoreField ignoreField  = MybatisTenantIgnoreManager.INSTANCE.getValue();
        if (ignoreField != null && ignoreField.getTenantId() == true) {
            return true;
        }
        // 如果表名在忽略的表列表中，则返回true表示忽略该表
        return IGNORED_TABLES.contains(tableName.toLowerCase());
    }
}